import requests
requests.packages.urllib3.util.ssl_.DEFAULT_CIPHERS = "TLS13-CHACHA20-POLY1305-SHA256:TLS13-AES-128-GCM-SHA256:TLS13-AES-256-GCM-SHA384:ECDHE:!COMPLEMENTOFDEFAULT"
import json
import os
import time

#我的推送      
class MyPush():
    myPush = {
     "ServerChan" :{
     	    "sendkey" : ""
     	    },
     	"wechat" : {
     		    # 应用ID
         "AgentId" : '',
         # 应用Secret
         "Secret" : '',
         # 企业ID
         "CompanyId" : ''   		   
     		   }
	    }
	   
    def __init__(self,myPush):
        for key,values in myPush.items():
            setattr(self,key,values)
        self.myPush = myPush
        
    def push(self,msg,pushType = "sendWechat"):
        if pushType == "sendWechat":
            self.sendWechat(msg)
        elif pushType == "ServerChan":
            self.server(msg)
        
    #server酱推送
    def server(self,desp,title=""):
        ##发送签到信息到server酱
        data = {
        	    "title" : title,
        	    "desp" : desp
        	}
        requests.post(url=f'https://sctapi.ftqq.com/{self.ServerChan["sendkey"]}.send',data=data) 

    def getFile(self,pathName):
        with open(pathName,mode="r") as f:
            return f.read()
             
    def writeFile(self,pathName,dict_a):
        pathDir = pathName[0:pathName.rfind("/")]
        if os.path.exists(pathDir) == False:
            os.makedirs(pathDir)
        with open(pathName,mode="w+") as f:
            f.write(json.dumps(dict_a,indent=4,ensure_ascii=False))
    #按固定字节截取字符串,微信支持最大字节2048
    def cut_str_to_bytes(self,s, max_bytes,strList):
        # cut it twice to avoid encoding potentially GBs of `s` just to get e.g. 10 bytes?
        b = s[:max_bytes].encode('utf-8')[:max_bytes]
    
        if b[-1] & 0b10000000:
            last_11xxxxxx_index = [i for i in range(-1, -5, -1)
                                   if b[i] & 0b11000000 == 0b11000000][0]
            # note that last_11xxxxxx_index is negative
    
            last_11xxxxxx = b[last_11xxxxxx_index]
            if not last_11xxxxxx & 0b00100000:
                last_char_length = 2
            elif not last_11xxxxxx & 0b0010000:
                last_char_length = 3
            elif not last_11xxxxxx & 0b0001000:
                last_char_length = 4
    
            if last_char_length > -last_11xxxxxx_index:
                # remove the incomplete character
                b = b[:last_11xxxxxx_index]
        
        mystr = b.decode('utf-8')
        strList.append(mystr)
        if len(s) > len(mystr):
            s = s[len(mystr):]
            if len(s) > len(mystr):
                self.cut_str_to_bytes(s, max_bytes,strList)
            else:
                strList.append(s)
    #获取token
    def GetTokenFromServer(self,Corpid, Secret,Token):
        """获取access_token"""
        Url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken"
        Data = {
            "corpid": Corpid,
            "corpsecret": Secret
        }
        r = requests.get(url=Url, params=Data, verify=False)
        if r.json()['errcode'] != 0:
            return False
        else:
            Token['access_token'] = r.json()['access_token']
            Token['time'] = time.time()
            return Token            
    
    #企业微信推送 
       
    def sendWechat(self,message):
        Token = {
	   	       "access_token" : "公众微信访问令牌",
	   	       "time": "令牌创建时间两个小时失效"
	       }
	       #判断是否为腾讯云函数环境
        scf = os.environ.get('TENCENTCLOUD_RUNENV')
        global path
        if scf == "SCF":
            Token_config = "/tmp/token.json"
        else:
            Token_config = "mytemp/myPush/token.json"
        #发送消息
        # 获取token信息
        if os.path.exists(Token_config):
            Token = json.loads(self.getFile(Token_config))
            if (time.time() - float(Token["time"]))> 7200:
                if self.GetTokenFromServer(self.wechat["CompanyId"], self.wechat["Secret"],Token) != False:
                    self.writeFile(Token_config,Token)                
            
        else:
            if self.GetTokenFromServer(self.wechat["CompanyId"], self.wechat["Secret"],Token) != False:
                self.writeFile(Token_config,Token)
        strList = []
        self.cut_str_to_bytes(message, 2048,strList)
        if strList != []:
            for index in range(len(strList)):
                message = strList[index]
                #要发送的信息格式
                data = {
                    "touser": "@all",
                    "msgtype": "text",
                    "agentid": f"{self.wechat.get('AgentId')}",
                    "text": {"content": f"{message}"}
                }
                # 字典转成json，不然会报错
                data = json.dumps(data)
                # 发送消息
                r = requests.post(f'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={Token["access_token"]}', data=data)